package com.example.userservice.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.cloudcommon.po.IdcOperateLog;
import com.example.cloudcommon.po.IdcUser;
import com.example.userservice.service.IdcOperateLogService;
import com.example.userservice.service.IdcUserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
public class UserController {

    @Autowired
    private IdcUserService idcUserService;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private Gson gson;

    @Autowired
    private IdcOperateLogService idcOperateLogService;

    @GetMapping("/users")
    public List<IdcUser> users() throws Exception {
        Page<IdcUser> page = new Page(1, 2);
        QueryWrapper<IdcUser> uwrapper = new QueryWrapper<>();
        page = idcUserService.page(page,uwrapper);
        return page.getRecords();
    }

    @GetMapping("/operate/logs")
    public List<IdcOperateLog> logs() throws Exception {
        QueryWrapper<IdcOperateLog> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("CREATE_TIME");
        wrapper.last("limit 10");
        return idcOperateLogService.list( wrapper);
    }

    @GetMapping("/users/hello")
    public ResponseEntity<?> hello() throws Exception {
        Map<String, String> map = new HashMap<>();
//        map.put("message", objectMapper.writeValueAsString(idcUserService.list()));

        Page page = new Page(1, 2);
        QueryWrapper<IdcUser> uwrapper = new QueryWrapper<>();
        Page users = idcUserService.page(page,uwrapper);

        IdcOperateLog log = new IdcOperateLog();
        log.setModule("test");
        log.setCreateTime(LocalDateTime.now());
        idcOperateLogService.save( log);

        QueryWrapper<IdcOperateLog> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("ID");
        IPage<IdcOperateLog> list = idcOperateLogService.page(page,wrapper);
        map.put("message", gson.toJson(list));
        return ResponseEntity.ok(map);

    }

    public static void main(String[] args) {
        System.out.println(new Date());
        System.out.println(LocalDateTime.now());
    }
}